package com.jt.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Configuration
@Slf4j
public class RabbitmqConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Resource
    private RabbitTemplate rabbitTemplate;

    /*@PostConstruct在对象创建之后立即执行*/
    @PostConstruct
    public void initRabbitmq() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        /*发送在交换机上成功或者失败都会调用*/
        log.info("confirm回调:" + correlationData);
        log.info("confirm--ACK:" + b);
        log.info("confirm--原因:" + s);
    }

    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        /*发送在队列上失败才会调用，成功不会调用*/
        log.info("returnedMessage失败回调-消息体:" + returnedMessage.getMessage().getBody().toString());
        log.info("returnedMessage失败回调-状态码:" + returnedMessage.getReplyCode());
        log.info("returnedMessage失败回调-应答码:" + returnedMessage.getReplyText());
        log.info("returnedMessage失败回调-交换机:" + returnedMessage.getExchange());
        log.info("returnedMessage失败回调-路由键:" + returnedMessage.getRoutingKey());

    }
}
